package com.erqi.time;

import com.erqi.dao.plcDao;
import com.erqi.dao.sqlServerDao;
import com.erqi.mapper.second.SqlServerPlcDataMapper;
import com.erqi.pojo.Message;
import com.erqi.pojo.PLCResources;
import com.erqi.pojo.Qrandplc;
import com.erqi.util.SnowflakeIdWorker;
import com.github.s7connector.api.DaveArea;
import com.github.s7connector.api.S7Connector;
import com.github.s7connector.api.factory.S7ConnectorFactory;
import com.github.s7connector.exception.S7Exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author king
 * @Date 2020/7/28 14:11
 * @Version 1.0
 */
@Configuration
@Slf4j
public class newTime {

    @Autowired
    plcDao qrMapper;
    @Autowired
    PLCResources plcResources;
    @Autowired
    Message message;
    @Autowired
    sqlServerDao serverDao;

    Map<String,String> mapK = new LinkedHashMap<>();
    Map<String,String> mapT = new LinkedHashMap<>();
    S7Connector connector =null;

    public newTime() {
        mapK.put("11","BT");
        mapK.put("12","BT");
        mapK.put("13","BT");
        mapK.put("14","BT");
        mapK.put("15","BT");
        mapK.put("16","BT");
        mapK.put("17","BT");
        mapK.put("18","BT");
        mapK.put("19","BT");
        mapK.put("20","BT");
        mapK.put("21","BT");
        mapK.put("22","BT");
        mapK.put("23","BT");


        mapT.put("17","BT");
        mapT.put("18","BT");
        mapT.put("19","BT");
        mapT.put("20","BT");
        mapT.put("21","BT");
        mapT.put("22","BT");
        mapT.put("23","BT");
        mapT.put("24","BT");
        mapT.put("25","BT");
        mapT.put("26","BT");
        mapT.put("27","BT");
        mapT.put("28","BT");
        mapT.put("29","BT");
        mapT.put("30","BT");
        mapT.put("31","BT");
        mapT.put("32","BT");
        mapT.put("33","BT");
        mapT.put("34","BT");
        mapT.put("35","BT");
        mapT.put("36","BT");
    }


    @Scheduled(fixedDelay = 4000)
    public synchronized void ScheduledPLCToMysql1line(){


        if (plcResources.isOne()){
            try{
                log.info("1———   开始连接   ———");
                connector =  S7ConnectorFactory
                        .buildTCPConnector()
                        .withHost(plcResources.getIp1()) //plc 地址
                        .withRack(plcResources.getRack()) //架机号
                        .withSlot(plcResources.getSlot()) //插槽号
                        .build();
                log.info("1———   连接成功   ———");
                log.info("1———   开始读取数据   ———");
                readK("1",816,"11",message.getOneKUser());
                readK("1",1328,"12",message.getOneKUser());
                readK("1",1840,"13",message.getOneKUser());
                readT("1",3122,"17",message.getOneTUser());
                readT("1",2866,"18",message.getOneTUser());
                readT("1",2610,"19",message.getOneTUser());
                readT("1",2354,"20",message.getOneTUser());
                readT("1",3378,"21",message.getOneTUser());
            }
            catch (S7Exception e){
                log.error("1S7Exception 出现异常了");
                try {
                    if(connector!=null){
                        connector.close();
                    }
                } catch (IOException ioException) {
                    log.error("1IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("1connector 关闭时出现异常");
                }
                connector=null;
                log.error("1异常代码：{}-{}",e.getLocalizedMessage(),e.getMessage());
                log.error("1connector 关闭了 并赋值空");
            }catch(Exception e){
                log.error("1ALL出现异常了");
                try {
                    connector.close();
                } catch (IOException ioException) {
                    log.error("1IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("1connector 关闭时出现异常");
                }
                connector=null;
                log.error("1异常代码：{}-{}",e.getLocalizedMessage(),e.getMessage());
                log.error("1connector赋值空 ALL异常");
            }finally {
                try {
                    if (connector==null){
                        log.error("1connector 为空不能关闭");
                    }else{
                        connector.close();
                    }
                } catch (IOException ioException) {
                    log.error("1IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("1connector 关闭时出现异常");
                }
                log.info("1---- 关闭连接 --");
                log.info("1---- end --");
            }
        }else{
            log.info("1 line未启用");
        }
    }

    @Scheduled(fixedDelay = 4500)
    public synchronized void ScheduledPLCToMysql2line(){
        if (plcResources.isTwo()){
            try{
                log.info("2———   开始连接   ———");
                connector =  S7ConnectorFactory
                        .buildTCPConnector()
                        .withHost(plcResources.getIp2()) //plc 地址
                        .withRack(plcResources.getRack()) //架机号
                        .withSlot(plcResources.getSlot()) //插槽号
                        .build();
                log.info("2———   连接成功   ———");
                log.info("2———   开始读取数据   ———");
                readK("2",816,"14",message.getTwoKUser());
                readK("2",1328,"15",message.getTwoKUser());
                readK("2",1840,"16",message.getTwoKUser());
                readT("2",3122,"22",message.getTwoTUser());
                readT("2",2866,"23",message.getTwoTUser());
                readT("2",2610,"24",message.getTwoTUser());
                readT("2",2354,"25",message.getTwoTUser());
                readT("2",3378,"26",message.getTwoTUser());
            }
            catch (S7Exception e){
                log.error("2S7Exception 出现异常了");
                try {
                    if(connector!=null){
                        connector.close();
                    }
                } catch (IOException ioException) {
                    log.error("2IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("2connector 关闭时出现异常");
                }
                connector=null;
                log.error("2异常代码：{}-{}",e.getLocalizedMessage(),e.getMessage());
                log.error("2connector 关闭了 并赋值空");
            }catch(Exception e){
                log.error("2ALL出现异常了");
                try {
                    connector.close();
                } catch (IOException ioException) {
                    log.error("2IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("2connector 关闭时出现异常");
                }
                connector=null;
                log.error("2异常代码：{}-{}",e.getLocalizedMessage(),e.getMessage());
                log.error("2connector赋值空 ALL异常");
            }finally {
                try {
                    if (connector==null){
                        log.error("2connector 为空不能关闭");
                    }else{
                        connector.close();
                    }
                } catch (IOException ioException) {
                    log.error("2IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("2connector 关闭时出现异常");
                }
                log.info("2---- 关闭连接 --");
                log.info("2---- end --");
            }
        }else{
            log.info("2 line未启用");
        }

    }

    @Scheduled(fixedDelay = 5000)
    public synchronized void ScheduledPLCToMysql3line(){
        if (plcResources.isThree()){
            try{
                log.info("3———   开始连接   ———");
                connector =  S7ConnectorFactory
                        .buildTCPConnector()
                        .withHost(plcResources.getIp3()) //plc 地址
                        .withRack(plcResources.getRack()) //架机号
                        .withSlot(plcResources.getSlot()) //插槽号
                        .build();
                log.info("3———   连接成功   ———");
                log.info("3———   开始读取数据   ———");
                readK("3",816,"17",message.getThreeKUser());
                readK("3",1328,"18",message.getThreeKUser());
                readK("3",1840,"19",message.getThreeKUser());
                readT("3",3122,"27",message.getThreeTUser());
                readT("3",2866,"28",message.getThreeTUser());
                readT("3",2610,"29",message.getThreeTUser());
                readT("3",2354,"30",message.getThreeTUser());
                readT("3",3378,"31",message.getThreeTUser());
            }
            catch (S7Exception e){
                log.error("3S7Exception 出现异常了");
                try {
                    if(connector!=null){
                        connector.close();
                    }
                } catch (IOException ioException) {
                    log.error("3IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("3connector 关闭时出现异常");
                }
                connector=null;
                log.error("3异常代码：{}-{}",e.getLocalizedMessage(),e.getMessage());
                log.error("3connector 关闭了 并赋值空");
            }catch(Exception e){
                log.error("3ALL出现异常了");
                try {
                    connector.close();
                } catch (IOException ioException) {
                    log.error("3IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("3connector 关闭时出现异常");
                }
                connector=null;
                log.error("3异常代码：{}-{}",e.getLocalizedMessage(),e.getMessage());
                log.error("3connector赋值空 ALL异常");
            }finally {
                try {
                    if (connector==null){
                        log.error("3connector 为空不能关闭");
                    }else{
                        connector.close();
                    }
                } catch (IOException ioException) {
                    log.error("3IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("3connector 关闭时出现异常");
                }
                log.info("3---- 关闭连接 --");
                log.info("3---- end --");
            }
        }else{
            log.info("3 line未启用");
        }

    }

    @Scheduled(fixedDelay = 5500)
    public synchronized void ScheduledPLCToMysql4line(){
        if (plcResources.isFour()){
            try{
                log.info("4———   开始连接   ———");
                connector =  S7ConnectorFactory
                        .buildTCPConnector()
                        .withHost(plcResources.getIp4()) //plc 地址
                        .withRack(plcResources.getRack()) //架机号
                        .withSlot(plcResources.getSlot()) //插槽号
                        .build();
                log.info("4———   连接成功   ———");
                log.info("4———   开始读取数据   ———");
                readK("4",816,"23",message.getFourKUser());
                readK("4",1328,"22",message.getFourKUser());
                readK("4", 1840,"21",message.getFourKUser());
                readT("4",3122,"32",message.getFourTUser());
                readT("4",2866,"33",message.getFourTUser());
                readT("4",2610,"34",message.getFourTUser());
                readT("4",2354,"35",message.getFourTUser());
                readT("4",3378,"36",message.getFourTUser());
            }
            catch (S7Exception e){
                log.error("4S7Exception 出现异常了");
                try {
                    if(connector!=null){
                        connector.close();
                    }
                } catch (IOException ioException) {
                    log.error("4IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("4connector 关闭时出现异常");
                }
                connector=null;
                log.error("4异常代码：{}-{}",e.getLocalizedMessage(),e.getMessage());
                log.error("4connector 关闭了 并赋值空");
            }catch(Exception e){
                log.error("4ALL出现异常了");
                try {
                    connector.close();
                } catch (IOException ioException) {
                    log.error("4IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("4connector 关闭时出现异常");
                }
                connector=null;
                log.error("4异常代码：{}-{}",e.getLocalizedMessage(),e.getMessage());
                log.error("4connector赋值空 ALL异常");
            }finally {
                try {
                    if (connector==null){
                        log.error("4connector 为空不能关闭");
                    }else{
                        connector.close();
                    }
                } catch (IOException ioException) {
                    log.error("4IO异常代码：{}-{}",ioException.getLocalizedMessage(),ioException.getMessage());
                    log.error("4connector 关闭时出现异常");
                }
                log.info("4---- 关闭连接 --");
                log.info("4---- end --");
            }
        }else{
            log.info("4 line未启用");
        }

    }

    public int PLCToMysqlMethodByK(String Num_machine, String QRcode, String Num_roBot ,String username){
        if (!"".equals(Num_machine)&&!"".equals(QRcode)){
            //检测第一个数字是否为0
            if(QRcode.charAt(0) == '0'){
                log.info("{}line————   {}#检测到 0 不做处理   ———",Num_roBot,Num_machine);
                return 0;
            }
            Qrandplc plCdata = new Qrandplc();
            plCdata.setDate(new Date());
            plCdata.setNumRobot(Num_roBot);
            plCdata.setWorkshop("2");//车间名称
            plCdata.setMonitor(message.getMonitor());


            int i_mySql = qrMapper.checkPLCData_mySql("开方机", QRcode);
           // int i_sqlServer = serverDao.checkPLCData_sqlServer("开方机", QRcode);

            if (i_mySql<=0){
                log.info("———数据库内无数据  ————");
                plCdata.setState1("入库成功");

            }else{
                log.info("———数据库内存在数据以修改状态");
                //plCdata.setState1("入库成功");
                plCdata.setState1("重复");
            }
            plCdata.setType("开方机");
            plCdata.setQrcode(QRcode);
            plCdata.setNumMachine(Num_machine);
            plCdata.setUser(username);
            int saveMysql = qrMapper.insertSelective(plCdata);

            try{
                serverDao.SavePLCData(plCdata);
            }catch (Exception e){
                if (saveMysql==1){
                    log.info("—— 当前用户为 ——"+username);
                    return 2;
                }else{
                    log.info("—— Mysql 保存失败 ——");
                    return 0;
                }
            }

            if (saveMysql==1){
                log.info("—— 当前用户为 ——"+username);
                return 1;
            }else{
                log.info("—— Mysql 保存失败 ——");
                return 0;
            }
        }else{
            return 0;//0为空
        }
    }

    public int PLCToMysqlMethodByT(String Num_machine,String QRcode,String Num_roBot,String username){
        if (!"".equals(Num_machine)&&!"".equals(QRcode)){
            //检测第一个数字是否为0
            if(QRcode.charAt(0) == '0'){
                log.info("{}line————   {}#检测到 0 不做处理   ———",Num_roBot,Num_machine);
                return 0;
            }
            Qrandplc plCdata = new Qrandplc();
            plCdata.setDate(new Date());
            plCdata.setNumRobot(Num_roBot);
            plCdata.setWorkshop("2");//车间名称
            plCdata.setMonitor(message.getMonitor());



            int i_mySql = qrMapper.checkPLCData_mySql("一体机", QRcode);
            //int i_sqlServer = serverDao.checkPLCData_sqlServer("一体机", QRcode);

            if (i_mySql<=0){
                log.info("———数据库内无数据  ————");
                plCdata.setState1("入库成功");
            }else{
                log.info("———数据库内存在数据以修改状态");
                plCdata.setState1("重复");
            }
            plCdata.setType("一体机");
            plCdata.setQrcode(QRcode);
            plCdata.setNumMachine(Num_machine);
            plCdata.setUser(username);
            int saveMysql = qrMapper.insertSelective(plCdata);
            try{
                serverDao.SavePLCData(plCdata);
            }catch (Exception e){
                if (saveMysql==1){
                    log.info("—— 当前用户为 ——"+username);
                    return 2;
                }else{
                    log.info("—— Mysql 保存失败 ——");
                    return 0;
                }
            }

            if (saveMysql==1){
                log.info("—— 当前用户为 ——"+username);
                return 1;
            }else{
                log.info("—— Mysql 保存失败 ——");
                return 0;
            }
        }else{
            return 0;//0为空
        }
    }

    public void readK(String roBot,int offset,String machine,String username){
        String plcData =new String(connector.read(DaveArea.DB, plcResources.getAreaNumber(), 15,offset),StandardCharsets.UTF_8).trim(); //开方机地址已经+2
        if (!mapK.get(machine).equals(plcData)){
            log.info("{}line-{}#读数据为：{}",roBot,plcData,machine);
            log.info("{}line—— {}#开始进行入库操作   ——",roBot,machine);
            int i = PLCToMysqlMethodByK(machine, mapK.get(machine), roBot ,username);
            if (i==1){
                log.info("{}line————   {}#数据入库成功   ———",roBot,machine);
                mapK.put(machine,plcData);
            }else if(i==2){
                log.info("{}line————   {}#sqlServer数据入库失败   ———",roBot,machine);

            } else{
                log.info("{}line————   {}#数据入库失败   ———",roBot,machine);
            }

        }else{
            log.info("{}line—{}#读数据为：{}",roBot,machine,plcData);
            log.info("{}line——— {}#数据相同不进行操作   ——",roBot,machine);
        }
    }

    public void readT(String roBot,int offset,String machine,String username){
        String plcData =new String(connector.read(DaveArea.DB, plcResources.getAreaNumber(), 15,offset),StandardCharsets.UTF_8).trim();//一体机地址已经+2
        if (!mapT.get(machine).equals(plcData)){
            log.info("{}line—{}#读数据为：{}",roBot,machine,plcData);
            log.info("{}line——— {}#开始进行入库操作   ——",roBot,machine);
            int i = PLCToMysqlMethodByT(machine, mapT.get(machine), roBot,username);
            if (i==1){
                log.info("{}line————   {}#数据入库成功   ———",roBot,machine);
                mapT.put(machine,plcData);
            } if(i==2){
                log.info("{}line————   {}#sqlServer数据入库失败   ———",roBot,machine);
            }
            else{
                log.info("{}line————   {}#数据入库失败   ———",roBot,machine);
            }
        }else{
            log.info("{}line—{}#读数据为：{}",roBot,machine,plcData);
            log.info("{}line——— {}#数据相同不进行操作   ——",roBot,machine);
        }
    }







   // @Scheduled(fixedDelay = 10000)
    public void test2(){
        log.info("———   开始连接   ———");
        connector =  S7ConnectorFactory
                .buildTCPConnector()
                .withHost(plcResources.getIp1()) //plc 地址
                .withRack(plcResources.getRack()) //架机号
                .withSlot(plcResources.getSlot()) //插槽号
                .build();
        log.info("———   连接成功   ———");
        log.info("———   开始读取数据   ———");
        byte[] read = connector.read(DaveArea.DB, plcResources.getAreaNumber(), plcResources.getBytes(), plcResources.getOffset());
        log.info("666-{}",new String(read));
    }

    //@Scheduled(fixedDelay = 10000)
    public void test5(){

        Qrandplc plCdata = new Qrandplc();
        plCdata.setDate(new Date());
        plCdata.setNumRobot("1");
        plCdata.setWorkshop("2");//车间名称
        plCdata.setType("开方机");
        plCdata.setQrcode("1");
        plCdata.setNumMachine("1");
        plCdata.setUser("1");
        serverDao.SavePLCData(plCdata);
    }
}
